package com.bwie.house.service.impl;

import com.alibaba.fastjson.JSON;
import com.bwie.house.entity.SubwayEntity;
import com.bwie.house.vo.FlatsSearchVo;
import com.bwie.house.vo.FlatsVo;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.Query;

import com.bwie.house.dao.FlatsDao;
import com.bwie.house.entity.FlatsEntity;
import com.bwie.house.service.FlatsService;

@SuppressWarnings("all")
@Service("flatsService")
public class FlatsServiceImpl extends ServiceImpl<FlatsDao, FlatsEntity> implements FlatsService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<FlatsEntity> w = new QueryWrapper<>();
        //获取 省的ID进行精确查找
        String m1 = (String) params.get("m1");
        //获取 市的ID进行精确查找
        String m2 = (String) params.get("m2");
        //获取地铁线路进行模糊查找
        String m3 = (String) params.get("m3");
        //获取楼盘名称进行模糊查找
        String m4 = (String) params.get("m4");

        //如果省不能与空和空字符串  进行精确查找
        if(StringUtils.isNotEmpty(m1) && m1!=""){
            w.eq("shen_id",m1);
        }
        //如果市不能与空和空字符串  进行精确查找
        if(StringUtils.isNotEmpty(m2) && m2!=""){
            w.eq("shi_id",m2);
        }

        //如果市不能与空和空字符串  进行精确查找
        if(StringUtils.isNotEmpty(m3) && m3!=""){
            w.eq("xian_id",m3);
        }
        //如果地铁线路进行精确查找  进行模糊查找
        if(StringUtils.isNotEmpty(m4) && m4!=""){
            w.like("flats_name",m4);
        }
        IPage<FlatsEntity> page = this.page(
                new Query<FlatsEntity>().getPage(params),
                w
        );

        return new PageUtils(page);
    }


    //存入ES
    @Override
    public List<FlatsVo> flatsvoEs() {
        return baseMapper.flatsvoEs();
    }

    @Override
    public PageUtils FlatsEsList(FlatsSearchVo flatsSearchVo) {

        SearchRequest searchRequest = new SearchRequest("flats");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();


        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //判断  楼盘名称 不为空和空字符串
        if(StringUtils.isNotEmpty(flatsSearchVo.getFlatsName()) && flatsSearchVo.getFlatsName()!=""){
//            楼盘名称模糊查找
            MatchQueryBuilder flats_name = QueryBuilders.matchQuery("flatsName", flatsSearchVo.getFlatsName());
            boolQueryBuilder.must(flats_name);
        }

//        楼盘地址
        if(StringUtils.isNotEmpty(flatsSearchVo.getFlatsAddress()) && flatsSearchVo.getFlatsAddress()!=""){
//            楼盘名称模糊查找
            MatchQueryBuilder flats_address = QueryBuilders.matchQuery("flatsAddress", flatsSearchVo.getFlatsAddress());
            boolQueryBuilder.must(flats_address);
        }

//        地区id(县id)
        if(flatsSearchVo.getXianId()!=null){
//             地区id(县id)
            MatchQueryBuilder flats_address = QueryBuilders.matchQuery("xianId", flatsSearchVo.getXianId());
            boolQueryBuilder.must(flats_address);
        }

//         private BigDecimal flatsAvgPrice1;
        if(flatsSearchVo.getFlatsAvgPrice1()!=null){
//            楼盘均价
            RangeQueryBuilder flatsAvgPrice = QueryBuilders.rangeQuery("flatsAvgPrice").gte(flatsSearchVo.getFlatsAvgPrice1());
            boolQueryBuilder.must(flatsAvgPrice);
        }
//    private BigDecimal flatsAvgPrice2;
        if(flatsSearchVo.getFlatsAvgPrice2()!=null){
//            楼盘均价o
            RangeQueryBuilder flatsAvgPrice = QueryBuilders.rangeQuery("flatsAvgPrice").lte(flatsSearchVo.getFlatsAvgPrice2());
            boolQueryBuilder.must(flatsAvgPrice);
        }

//         /**
//     * 装修情况（1 毛坯 2简装 3精装 4豪装）
//     */
//    private Integer decolate;
        if(flatsSearchVo.getDecolate()!=null){
//               * 装修情况（1 毛坯 2简装 3精装 4豪装）
            MatchQueryBuilder decolate = QueryBuilders.matchQuery("decolate", flatsSearchVo.getDecolate());
            boolQueryBuilder.must(decolate);
        }

        searchSourceBuilder.query(boolQueryBuilder);
//    //排序状态   0-默认  1-价格低到高  2-价格高到低  3-开盘时间 正  4-开盘时间  desc  不存在的字段
//    private Integer status=0;   //四种情况  else 0
        if(flatsSearchVo.getStatus()!=null){
//            1-价格低到高
            if(flatsSearchVo.getStatus()==1){
                searchSourceBuilder.sort("flatsAvgPrice", SortOrder.ASC);
//                2-价格高到低
            }else if(flatsSearchVo.getStatus()==2){
                searchSourceBuilder.sort("flatsAvgPrice", SortOrder.DESC);
//                3-开盘时间
            }else if(flatsSearchVo.getStatus()==3){
                searchSourceBuilder.sort("starttime", SortOrder.ASC);
//                4-开盘时间  desc
            }else if(flatsSearchVo.getStatus()==4){
                searchSourceBuilder.sort("starttime", SortOrder.DESC);
            }else{
                //默认按照 id 升序
                searchSourceBuilder.sort("flatsId", SortOrder.ASC);
            }
        }
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            TotalHits totalHits = searchResponse.getHits().getTotalHits();
            Long value = totalHits.value;
            SearchHit[] hits = searchResponse.getHits().getHits();
            List<FlatsEntity> collect = Arrays.stream(hits).map(h -> {
                FlatsEntity flatsEntity = JSON.parseObject(h.getSourceAsString(), FlatsEntity.class);
                return flatsEntity;
            }).collect(Collectors.toList());
            return new PageUtils(collect,value.intValue(),1,3);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}